package com.coocaa.x.service.litecontent.providers.store.host.com_coocaa_hall;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.litecontent.LiteContentProvider;
import com.coocaa.x.service.litecontent.LiteContentProvider.LiteContentProviderHost;
import com.coocaa.x.service.litecontent.LiteContentProvider.ResourceHandler;
import com.coocaa.x.service.litecontent.data.ResultPackage;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_ADInfo;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_ADInfo.ADInfo_Item;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_Content;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_Content.Head;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_TagList;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_hall.RP_TagList.Tag_Item;
import com.coocaa.x.service.litecontent.providers.store.host.com_coocaa_hall.data.TagContentData;
import com.coocaa.x.service.litecontent.providers.store.host.com_coocaa_hall.data.TagListData;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.skyworth.framework.skysdk.util.MD5;
import com.skyworth.webSDK.webservice.tcappstore.AppAdInfo;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.GeneralZoneInfo;
import com.skyworth.webSDK.webservice.tcappstore.HallTag;
import com.skyworth.webSDK.webservice.tcappstore.HallTagList;
import com.skyworth.webSDK.webservice.tcappstore.TagContent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StoreHost_Com_Coocaa_Hall extends LiteContentProviderHost {
    private static StoreHost_Com_Coocaa_Hall instance = null;
    private Map<String, GeneralZoneInfo> zoneInfoMap = new HashMap<String, GeneralZoneInfo>();

    public static synchronized void create(Context context, LiteContentProvider provider) {
        if (instance == null)
            instance = new StoreHost_Com_Coocaa_Hall(context, provider);
    }

    private static final String MY_HOST = "com.coocaa.hall";
    private static final String OPERATIONACTION = "com.coocaa.hall.action";

    // private String mainDataMD5 = "";

    public StoreHost_Com_Coocaa_Hall(Context context, LiteContentProvider provider) {
        super(context, provider);
        // TODO Auto-generated constructor stub
    }

    @Override
    public String myHost() {
        // TODO Auto-generated method stub
        return MY_HOST;
    }

//    private ResourceHandler mainpageHandler = new ResourceHandler(this, "/mainpage")
//    {
//
//        private List<Mainpage_Item> getMainDataFromDB()
//        {
//            LogUtils.d("web", "getMainDataFromDB");
//            List<Mainpage_Item> mainResourceList = new ArrayList<Mainpage_Item>();
//            try
//            {
//                OperationMainPageData cache = new OperationMainPageData();
//                List<LiteDBSupport> caches = cache.selectAll();
//                if (caches != null && caches.size() > 0)
//                {
//                    for (LiteDBSupport data : caches)
//                    {
//                        OperationMainPageData oData = (OperationMainPageData) data;
//                        Mainpage_Item itme = new Mainpage_Item(oData.categoryid, oData.id,
//                                oData.name, oData.url, oData.icon, oData.type, oData.pkg,
//                                oData.mActivity, oData.version, oData.structure);
//                        mainResourceList.add(itme);
//                    }
//                }
//            } catch (Exception e)
//            {
//                e.printStackTrace();
//            }
//            return mainResourceList;
//        }
//
//        private void saveMainData(List<Mainpage_Item> list)
//        {
//            try
//            {
//                OperationMainPageData data = new OperationMainPageData();
//                data.deleteAll();
//                LogUtils.d("web", "saveMainData  delete db success");
//                for (Mainpage_Item item : list)
//                {
//                    data.setData(item.categoryid, item.id, item.name, item.url, item.icon,
//                            item.type, item.pkg, item.mActivity, item.version, item.structure);
//                    data.insert();
//                }
//            } catch (Exception e)
//            {
//                e.printStackTrace();
//            }
//        }
//
//        private List<Mainpage_Item> getMainDataFromWeb(boolean hasDB)
//        {
//            List<Mainpage_Item> list = new ArrayList<Mainpage_Item>();
//            try
//            {
//                OperationMainData data = null;
//                data = CoocaaApplication.getCoocaaWebService().getAppStoreService().getGeneralIndexData();
//                if (data != null && data.getList() != null && data.getList().size() > 0)
//                {
//                    for (OperationData oData : data.getList())
//                    {
//                        Mainpage_Item item = new Mainpage_Item(oData.getCategory(), oData.getId(),
//                                oData.getName(), oData.getUrl(), oData.getIcon(), oData.getType(),
//                                oData.getPkg(), oData.getmActivity(), oData.getVersion(),
//                                oData.getStructure());
//                        list.add(item);
//                    }
//                }
//            } catch (AppStoreException e)
//            {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            LogUtils.d("web", "getMainDataFromWeb  size:" + list.size());
//            if (list != null && list.size() > 0)
//            {
//                String dataMD5 = getMainDataMD5(list);
//                String mainDataMD5 = null;
////                try
////                {
////                    mainDataMD5 = XServiceManager.getLiteConfigService().getStringValue(
////                            "operation_md5", "");
////                } catch (RemoteException e)
////                {
////                    // TODO Auto-generated catch block
////                    e.printStackTrace();
////                }
//                LogUtils.d("web", "getMainDataFromWeb  dataMD5:" + dataMD5 + " mainDataMD5:"
//                        + mainDataMD5);
//                if (!dataMD5.equals(mainDataMD5))
//                {
//                    saveMainData(list);
////                    try
////                    {
////                        XServiceManager.getLiteConfigService().saveStringConfig("operation_md5",
////                                dataMD5);
////                    } catch (RemoteException e)
////                    {
////                        // TODO Auto-generated catch block
////                        e.printStackTrace();
////                    }
//                    if (hasDB)
//                        sendBroadcast();
//                }
//            }
//            return list;
//        }
//
//        private String getMainDataMD5(List<Mainpage_Item> list)
//        {
//            RP_Mainpage rp = new RP_Mainpage();
//            for (Mainpage_Item item : list)
//                rp.resource.add(item);
//            return MD5.md5s(rp.resource.toJSONString());
//        }
//
//        @Override
//        public RP_Mainpage call(Uri uri)
//        {
//            // TODO Auto-generated method stub
//            RP_Mainpage rp = new RP_Mainpage();
//            List<Mainpage_Item> mainList = getMainDataFromDB();
//            LogUtils.d("web", "call 0000 mainList:" + mainList.size());
//            if (mainList != null && mainList.size() > 0)
//            {
//                new Thread(new Runnable()
//                {
//
//                    @Override
//                    public void run()
//                    {
//                        // TODO Auto-generated method stub
//                        getMainDataFromWeb(true);
//                    }
//                }).start();
//                LogUtils.d("web", "call  size:" + mainList.size());
//                for (Mainpage_Item item : mainList)
//                    rp.resource.add(item);
//                return rp;
//            }
//
//            mainList = getMainDataFromWeb(false);
//            LogUtils.d("web", "call 222 size:" + mainList.size());
//            if (mainList != null && mainList.size() > 0)
//            {
//                for (Mainpage_Item item : mainList)
//                    rp.resource.add(item);
//                return rp;
//            }
//            return null;
//        }
//    };
//
//    private ResourceHandler lispageHandler = new ResourceHandler(this, "/listpage")
//    {
//        private List<Listpage_Item> getListpageData(int CategoryTypeId, int pageindex, int pagecount)
//        {
//            List<Listpage_Item> list = new ArrayList<Listpage_Item>();
//            try
//            {
//                GeneralAppList appList = null;
//                appList = CoocaaApplication.getCoocaaWebService().getAppStoreService()
//                            .getGeneralAppsByTopicId(CategoryTypeId, pageindex, pagecount);
//                if (appList != null && appList.getAppList() != null
//                        && appList.getAppList().size() > 0)
//                {
//                    for (OperationListData data : appList.getAppList())
//                    {
//                        Listpage_Item item = new Listpage_Item(data.id, data.icon, data.url,
//                                data.version, data.name, data.downloads, data.packagename,
//                                data.mainActivity, data.softwaresize, data.superscript);
//                        list.add(item);
//                    }
//                }
//            } catch (AppStoreException e)
//            {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            return list;
//        }
//
//        @Override
//        public ResultPackage call(Uri uri)
//        {
//            // TODO Auto-generated method stub
//            LogUtils.d("web", "store  call");
//            int id = Integer.parseInt(uri.getQueryParameter("id"));
//            int index = Integer.parseInt(uri.getQueryParameter("index"));
//            int count = Integer.parseInt(uri.getQueryParameter("count"));
//            LogUtils.d("web", "store  call   id:" + id + " index:" + index + " count:" + count);
//            RP_Listpage rp = new RP_Listpage();
//            List<Listpage_Item> pageList = getListpageData(id, index, count);
//            if (pageList != null && pageList.size() > 0)
//            {
//                LogUtils.d("web", "store  call  pagelist is not null  ");
//                for (Listpage_Item item : pageList)
//                    rp.resource.add(item);
//                return rp;
//            }
//            return null;
//        }
//
//    };

    private ResourceHandler adinfoHandler = new ResourceHandler(this, "/adinfo") {
        private List<ADInfo_Item> getADInfo(String name) {
            List<ADInfo_Item> reList = new ArrayList<ADInfo_Item>();
            try {
                AppAdInfo info = null;
                info = CoocaaApplication.getCoocaaWebService().getAppStoreService().getGeneralAd(name);
                LogUtils.d("web", "getADInfo  url:" + (info == null));
                if (info != null) {
                    LogUtils.d("web", "getADInfo  url:" + info.picUrl);
                    ADInfo_Item re = new ADInfo_Item(0, info.picUrl, info.smallPicUrl, info.linkUrl);
                    reList.add(re);
                }
            } catch (AppStoreException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return reList;
        }

        @Override
        public ResultPackage call(Uri uri) {
            // TODO Auto-generated method stub
            LogUtils.d("web", "call url:" + uri.toString());
            String name = uri.getQueryParameter("name");
            RP_ADInfo rp = new RP_ADInfo();
            List<ADInfo_Item> resouce = getADInfo(name);
            if (resouce != null && resouce.size() > 0) {
                LogUtils.d("web", "call resouce:" + resouce.toString());
                for (ADInfo_Item item : resouce)
                    rp.resource.add(item);
                return rp;
            }
            return null;
        }

    };

    private ResourceHandler zonePageHandler = new ResourceHandler(this, "/zonepage") {

        private RP_Content getZonePageJson(String id) {
            RP_Content rp = new RP_Content();
//            List<String> list = TestJson.getJson();
            List<String> list = new ArrayList<String>();
            String bg = "";
            boolean isOneKeySetup = false;
            GeneralZoneInfo zoneInfo = null;
            if (zoneInfoMap.containsKey(id)) {
                zoneInfo = zoneInfoMap.get(id);
                list = zoneInfo.getResource_items();
                bg = zoneInfo.getZonecover();
                isOneKeySetup = zoneInfo.getIsOneKey_install();
                LogUtils.d("json", "getZonePageJson from cache list.size:" + list.size() + " zonecover:" + bg);
            } else {
                try {
                    zoneInfo = CoocaaApplication.getCoocaaWebService().getAppStoreService().getZoneInfo(id);
                    if (zoneInfo != null) {
                        zoneInfoMap.put(id, zoneInfo);
                        list = zoneInfo.getResource_items();
                        bg = zoneInfo.getZonecover();
                        isOneKeySetup = zoneInfo.getIsOneKey_install();
                        LogUtils.d("json", "getZonePageJson from web list.size:" + list.size() + " zonecover:" + bg);
                    }
                } catch (AppStoreException e) {
                    e.printStackTrace();
                }
            }
            if (list != null && list.size() > 0 && bg != null && !bg.equals("")) {
                Head head = new Head();
                head.id = id;
//                head.bg_url = "http://www.uimaker.com/uploads/allimg/111201/1_111201101442_1.jpg";
                head.bg_url = bg;
                rp.head = head;
                rp.head.isOneKeySetup = isOneKeySetup;
                for (String item : list)
                    rp.resource.add(item);
            }
            return rp;
        }

        @Override
        public ResultPackage call(Uri uri) {
            String id = uri.getQueryParameter("id");
            RP_Content rp = null;
            rp = getZonePageJson(id);
            if (rp != null && rp.resource.total_count > 0) {
                return rp;
            }
            return null;
        }
    };

    private ResourceHandler contentHandler = new ResourceHandler(this, "/contentdata") {

        private RP_Content getContentDataFromDB(String id) {
            LogUtils.d("json", "getContentDataFromDB  begin ");
            RP_Content rp = new RP_Content();
            Head head = new Head();
            head.id = id;
            try {
                TagContentData cache = new TagContentData();
                List<LiteDBSupport> caches = cache.select(null, null, null, "id = ?", id);
                if (caches != null && caches.size() > 0) {
                    for (LiteDBSupport data : caches) {
                        TagContentData tData = (TagContentData) data;
                        head.title = tData.title;
                        head.type = tData.type;
                        rp.resource.add(tData.json);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            rp.head = head;
            LogUtils.d("json", "getContentDataFromDB     id:" + id + " size:" + rp.resource.total_count);
            return rp;
        }

        private void saveTagContent(String id, int type, String title, List<String> itemList) {
            LogUtils.d("json", "saveTagContent  begin   id:" + id + " size:" + itemList.size());
            try {
                TagContentData tData = new TagContentData();
                List<LiteDBSupport> list = tData.select(null, null, null, "id = ?", id);
                boolean notSame = false;
                if (list != null && list.size() > 0) {
                    LogUtils.d("json", "saveTagContent  size:" + list.size());
                    if (list.size() != itemList.size())
                        notSame = true;
                    else {
                        for (int i = 0; i < list.size(); i++) {
                            TagContentData data = (TagContentData) list.get(i);
                            if (!data.json.equals(itemList.get(i))) {
                                notSame = true;
                                continue;
                            }
                        }
                    }

                } else {
                    LogUtils.d("json", "saveTagContent insert  begin");
                    for (String item : itemList) {
                        tData.setData(id, type, title, item);
                        tData.insert();
                    }
                    LogUtils.d("json", "saveTagContent insert  success");
                }
                LogUtils.d("json", "saveTagContent  notSame:" + notSame);
                if (notSame) {
                    tData.delete("id = ?", id);

                    for (String item : itemList) {
                        tData.setData(id, type, title, item);
                        tData.insert();
                    }
                    LogUtils.d("json", "saveTagContent  success");
                }
                LogUtils.d("json", "saveTagContent  end");
            } catch (Exception E) {
                E.printStackTrace();
            }
        }

        private RP_Content getContentDataFromWeb(String id, int index, int count) {
            RP_Content rp = new RP_Content();
            LogUtils.d("json", "call getContentDataFromWeb ");
            //从后台获取数据
            try {
                TagContent content = CoocaaApplication.getCoocaaWebService().getAppStoreService().getContentById(id, String.valueOf(index), "12");
                if (content != null && content.getList() != null && content.getList().size() > 0) {
                    Head head = new Head();
                    head.id = id;
                    head.type = content.getTagType();
                    head.title = content.getTitle();
                    rp.head = head;
                    for (String c : content.getList()) {
                        rp.resource.add(c);
                    }
                }
            } catch (AppStoreException e) {
                e.printStackTrace();
            }
            LogUtils.d("json", "call getContentDataFromWeb 222  size:" + rp.resource.total_count);
            if (index == -1 && rp != null && rp.head != null && rp.resource.total_count > 0) {
                saveTagContent(id, rp.head.type, rp.head.title, rp.resource.resource_items);
            }
            return rp;
        }

        @Override
        public ResultPackage call(Uri uri) {
            final String id = uri.getQueryParameter("id");
            final String index = uri.getQueryParameter("index");
            final String count = uri.getQueryParameter("count");
            LogUtils.d("json", "call tagcontent   uri:" + uri.toString());
            RP_Content rp = new RP_Content();
            if (index.equals("-1"))     // 如果为-1，才有存储的数据
                rp = getContentDataFromDB(id);
            if (rp != null && rp.resource != null && rp.resource.total_count > 0) {
                LogUtils.d("json", "call tagcontent   size:" + rp.resource.total_count);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getContentDataFromWeb(id, Integer.parseInt(index), Integer.parseInt(count));
                    }
                }).start();
                return rp;
            }

            rp = getContentDataFromWeb(id, Integer.parseInt(index), Integer.parseInt(count));
            if (rp != null && rp.resource != null && rp.resource.total_count > 0) {
                LogUtils.d("json", "call tagcontent 222  size:" + rp.resource.total_count);
                return rp;
            }
            return null;
        }
    };

    private ResourceHandler tagHandler = new ResourceHandler(this, "/tagdata") {

        private synchronized List<Tag_Item> getTagListFromDB(String name) {
            List<Tag_Item> list = new ArrayList<Tag_Item>();
            try {
                TagListData cache = new TagListData();
                List<LiteDBSupport> caches = cache.select(null, null, null, "name = ?", name);
                if (caches != null && caches.size() > 0) {
                    for (LiteDBSupport data : caches) {
                        TagListData tData = (TagListData) data;
                        Tag_Item item = new Tag_Item(tData.id, tData.tagpic, tData.title, tData.total);
                        list.add(item);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return list;
        }

        private synchronized void saveTagList(String name, List<Tag_Item> list) {
            try {
                TagListData tData = new TagListData();
//                tData.deleteAll();
                tData.delete("name = ?", name);
                LogUtils.d("web", "saveMainData  delete db success");
                for (Tag_Item item : list) {
                    tData.setData(name, item.tagpic, item.id, item.title, item.total);
                    tData.insert();
                }

            } catch (Exception E) {
                E.printStackTrace();
            }
        }

        private List<Tag_Item> getTagListFromWeb(String name) {
            List<Tag_Item> list = new ArrayList<Tag_Item>();
            LogUtils.d("json", "taglist  getTagListFromWeb");
            //后台获取list
            try {
                HallTagList tagList = CoocaaApplication.getCoocaaWebService().getAppStoreService().getHallTagList(name);
                if (tagList != null && tagList.getTaglist() != null && tagList.getTaglist().size() > 0) {
                    String tagpic = tagList.getBanner_icon();
                    if (tagpic == null)
                        tagpic = "";
                    for (HallTag tag : tagList.getTaglist()) {
                        Tag_Item item = new Tag_Item(String.valueOf(tag.getId()), tagpic, tag.getTitle(), tag.getTotal());
                        list.add(item);
                    }
                }
            } catch (AppStoreException e) {
                e.printStackTrace();
            }
            LogUtils.d("json", "taglist  getTagListFromWeb  size:" + list.size());
            if (list != null && list.size() > 0) {
                saveTagList(name, list);
            }
            return list;
        }

        @Override
        public ResultPackage call(Uri uri) {
            final String name = uri.getQueryParameter("name");
            LogUtils.d("json", "taglist  call  uri:" + uri.toString());
            RP_TagList rp = new RP_TagList();
            List<Tag_Item> list = getTagListFromDB(name);
            LogUtils.d("json", "taglist  call  size:" + list.size());
            if (list != null && list.size() > 0) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getTagListFromWeb(name);
                    }
                }).start();

                for (Tag_Item item : list)
                    rp.resource.add(item);
                return rp;
            }

            list = getTagListFromWeb(name);
            LogUtils.d("json", "taglist 222 call  size:" + list.size());
            if (list != null && list.size() > 0) {
                for (Tag_Item item : list)
                    rp.resource.add(item);
                return rp;
            }
            return null;
        }
    };

    private String getMD5(String json) {
        return MD5.md5s(json);
    }

    private void sendBroadcast() {
        Intent i = new Intent();
        i.setAction(OPERATIONACTION);
        i.putExtra("data", "mainpage");
        mContext.sendBroadcast(i);
        LogUtils.d("web", "sendBroadcast!!");
    }

}
